import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-20
 * Time: 20:27
 */
public class UdpEchoServer {
    private DatagramSocket socket = null;
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //1.读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4086);
            socket.receive(requestPacket);
            //把读取到的二进制数据， 转换成字符串
            String request = new String(requestPacket.getData(),0, requestPacket.getLength());
            //2.根据请求，构造响应数据包
            String response = process(request);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length
                    ,requestPacket.getSocketAddress());
            //3.返回响应数据包
            socket.send(requestPacket);
            //4.打印日志
            System.out.printf("[%s:%d] req:%s, res:%s", requestPacket.getAddress().toString(), requestPacket.getPort(), request, response);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9090);
        udpEchoServer.start();
    }
}
